<template>
  <div>
    <div
      class="-mt-46 h-[calc(100vh-50px)] custom-navbar-wrapper pt-46 flex flex-col"
    >
      <NormalTabs
        :tabs="CATEGORIES.map(item => ({ id: item.id, name: item.name }))"
        :active-id="activeCategoryId"
        :tab-class="tabsTypeOneClass"
        @update:active-id="activeCategoryId = $event"
      />
      <div
        class="c-bg-FF4A35-10 px-15 h-46 w-full text-FF4A35 text-13 flex items-center"
      >
        生成的内容在线储存1年，到期后将无法查看或下载,失败数据3个月后自动清除
      </div>
      <div
        ref="scrollContainer"
        class="scroll-view scroll-view--vertical hide-scrollbar flex-1"
        :style="popoverVisible ? 'overflow-y: hidden;' : ''"
      >
        <div ref="scrollContent" class="scroll-view__content">
          <!-- 视频列表 -->
          <div v-if="activeCategoryId === 'video'" class="mx-15">
            <div
              v-for="item in historyData.video.records"
              :key="item.humanVideoMakeTaskId"
              class="py-20 border-b-1 border-solid border-F5F5F5 flex"
              @click="navigateTo('GenerateDetail', item.humanVideoMakeTaskId)"
            >
              <div
                class="w-100 h-100 relative rounded-10 bg-F6F7F8 overflow-hidden"
              >
                <img
                  class="w-100 h-100 object-contain"
                  :src="
                    item.cover ||
                    item.humanImageUrl ||
                    `${IMG_CDN_39}/common/history_cover_default.png`
                  "
                  alt=""
                />
                <div
                  v-if="item.videoStatus === HUMAN_IMG_STATUS_ENUM.MAKING"
                  class="c-translucent-balck50 c-animation-opacity size-full absolute left-0 top-0 z-2 flex flex-col items-center justify-center"
                >
                  <div class="loading-circle w-30 h-30 rounded-[50%]" />
                  <div class="mt-6 text-14 text-white">
                    {{ item.videoProgress }}%
                  </div>
                </div>
              </div>
              <div class="pl-15 flex flex-col flex-grow-1 w-0">
                <div class="flex items-start">
                  <div class="line-clamp-2 text-15 flex-grow-1 w-0">
                    {{ item.videoName }}
                  </div>
                  <CustomPopover
                    v-model:visible="popoverVisible"
                    placement="bottom-end"
                    :offset="[-5, 8]"
                  >
                    <template #reference>
                      <svg-icon
                        class="pl-5 py-5"
                        name="icon-gengduocaozuo"
                        :size="8"
                        color="#666"
                      />
                    </template>
                    <div>
                      <div
                        class="w-100 h-45 border-b-1 border-solid border-F5F5F5 flex justify-center items-center text-15"
                      >
                        下载保存
                      </div>
                      <div
                        class="w-100 h-45 border-b-1 border-solid border-F5F5F5 flex justify-center items-center text-15"
                      >
                        重命名
                      </div>
                      <div
                        class="w-100 h-45 border-b-1 border-solid border-F5F5F5 flex justify-center items-center text-15"
                      >
                        复制
                      </div>
                      <div
                        class="w-100 h-45 flex justify-center items-center text-15"
                      >
                        删除
                      </div>
                    </div>
                  </CustomPopover>
                </div>
                <div class="mt-8 text-13 text-999999">
                  创建时间：{{ item.videoCreateTime }}
                </div>
                <div
                  class="mt-auto px-6 leading-22 w-max rounded-4 text-13"
                  :class="{
                    'text-4D00FF bg-E2E0FF':
                      item.videoStatus === HUMAN_IMG_STATUS_ENUM.MAKING,
                    'text-17B459 c-bg-17B459-10':
                      item.videoStatus === HUMAN_IMG_STATUS_ENUM.SUCCESS,
                    'text-FF4A35 c-bg-FF4A35-10': [
                      HUMAN_IMG_STATUS_ENUM.FAIL,
                      HUMAN_IMG_STATUS_ENUM.EXPIRED
                    ].includes(item.videoStatus)
                  }"
                >
                  {{ STATUS_MAP[item.videoStatus] || "生成中" }}
                </div>
              </div>
            </div>
          </div>

          <!-- 图片列表 -->
          <div v-if="activeCategoryId === 'image'" class="ml-15">
            <div class="flex flex-wrap">
              <img
                v-for="(item, index) in historyData.image.records"
                :key="item.id"
                class="style-image-item mt-15 w-108 h-108 rounded-10 object-cover"
                :src="item.humanAiartUrl"
                alt="图片"
                @click="showImageViewer(index)"
              />
            </div>
          </div>

          <!-- 加载状态 -->
          <div v-if="isLoading" class="py-20 flex justify-center items-center">
            <van-loading size="24px" vertical>
              <span class="text-13 text-999 mt-10">加载中...</span>
            </van-loading>
          </div>

          <!-- 没有更多数据 -->
          <div
            v-if="
              isFinished && historyData[activeCategoryId].records.length > 0
            "
            class="py-15 text-center text-13 text-999"
          >
            <span class="inline-block px-10 py-5 rounded-full bg-gray-100"
              >没有更多数据了</span
            >
          </div>
          <!-- 空状态 -->
          <EmptyState
            v-if="
              !isLoading && historyData[activeCategoryId].records.length === 0
            "
            class="mt-50"
          />
        </div>
      </div>
    </div>

    <!-- 图片查看器组件 -->
    <ImageViewer
      v-model:visible="previewVisible"
      v-model:currentIndex="currentIndex"
      :images="mappedImages"
      @delete="handleDelete"
    />
  </div>
</template>
<script setup lang="ts">
import {
  onMounted,
  ref,
  watch,
  nextTick,
  onBeforeUnmount,
  computed
} from "vue";
import NormalTabs from "@/components/NormalTabs/index.vue";
import { getImageInfoList, getVideoInfoList } from "@/api/History";
import type { PageResponse } from "src/types";
import { IMG_CDN_39 } from "@/constants";
import { showToast } from "vant";
import { HUMAN_IMG_STATUS_ENUM } from "@/enums";
import router from "@/router";

defineOptions({
  name: "History"
});
// 导航到指定页面
const navigateTo = (routeName: string, Id: string) => {
  router.push({ name: routeName, params: { Id } });
};

// 分类配置
const CATEGORIES = [
  { id: "video", name: "视频", api: getVideoInfoList },
  { id: "image", name: "图片", api: getImageInfoList }
];
const activeCategoryId = ref<string>("video");

// 样式配置
const tabsTypeOneClass = ref({
  justifyContent: "justify-around",
  itemWidth: "w-140"
});

// 统一历史记录数据
const historyData = ref<Record<string, PageResponse<any>>>({
  video: { current: 1, pages: 0, records: [], size: 24, total: 0 },
  image: { current: 1, pages: 0, records: [], size: 24, total: 0 }
});

// 弹窗显示状态
const popoverVisible = ref(false);

// 加载状态
const isLoading = ref(false);
const isFinished = ref(false);

// 滚动容器引用
const scrollContainer = ref<HTMLElement | null>(null);
const scrollContent = ref<HTMLElement | null>(null);

// 状态映射
const STATUS_MAP = {
  SUCCESS: "已生成",
  FAIL: "生成失败",
  EXPIRED: "已失效"
};

// 统一加载函数
const loadHistoryData = async (loadMore = false) => {
  if (isLoading.value) return;

  try {
    isLoading.value = true;
    const category = activeCategoryId.value;
    const currentData = historyData.value[category];

    const nextPage = loadMore ? currentData.current + 1 : 1;
    const params = { pageNo: nextPage, pageSize: 24 };

    const apiFunc = CATEGORIES.find(c => c.id === category)?.api;
    if (!apiFunc) return;

    const res = await apiFunc(params);

    historyData.value[category] = loadMore
      ? { ...res, records: [...currentData.records, ...res.records] }
      : res;

    isFinished.value = res.current >= res.pages;

    if (loadMore && res.records.length > 0) {
      showToast({
        message: `加载了 ${res.records.length} 条新记录`,
        position: "bottom"
      });
    }
  } catch (error) {
    console.error("加载失败:", error);
    showToast("加载失败，请稍后再试");
  } finally {
    isLoading.value = false;
    nextTick(() => {
      if (scrollContainer.value && scrollContent.value) {
        scrollContainer.value.addEventListener("scroll", handleScroll);
      }
    });
  }
};

// 监听分类切换
watch(activeCategoryId, newId => {
  // 移除旧分类的滚动监听
  if (scrollContainer.value) {
    scrollContainer.value.removeEventListener("scroll", handleScroll);
  }
  // 清空其他分类的数据
  const otherCategory = newId === "video" ? "image" : "video";
  historyData.value[otherCategory] = {
    current: 1,
    pages: 0,
    records: [],
    size: 24,
    total: 0
  };
  // 加载新分类数据
  if (historyData.value[newId].records.length === 0) {
    loadHistoryData();
  }
});

// 处理滚动事件
const handleScroll = () => {
  if (
    !scrollContainer.value ||
    !scrollContent.value ||
    isLoading.value ||
    isFinished.value
  )
    return;

  const containerHeight = scrollContainer.value.clientHeight;
  const contentHeight = scrollContent.value.scrollHeight;
  const scrollTop = scrollContainer.value.scrollTop;
  const distanceToBottom = contentHeight - (scrollTop + containerHeight);

  if (distanceToBottom < 50) {
    scrollContainer.value.removeEventListener("scroll", handleScroll);
    loadHistoryData(true);
  }
};

const mappedImages = computed(() =>
  historyData.value.image.records.map(item => ({
    url: item.humanAiartUrl,
    createTime: item.createTime
  }))
);

const previewVisible = ref(false);
const currentIndex = ref(0);

const showImageViewer = index => {
  currentIndex.value = index;
  previewVisible.value = true;
};

const handleDelete = index => {
  historyData.value[activeCategoryId.value].records.splice(index, 1);
};

onMounted(() => {
  // 初始加载当前分类数据
  loadHistoryData();
});

onBeforeUnmount(() => {
  if (scrollContainer.value) {
    scrollContainer.value.removeEventListener("scroll", handleScroll);
  }
});
</script>

<style scoped lang="less">
.custom-navbar-wrapper {
  min-height: 100%;
  background-image: linear-gradient(
    180deg,
    #d5e2ff 0%,
    #ffffff 16%,
    #ffffff 100%
  );
  background-repeat: no-repeat;
}

.loading-circle {
  border: 3px solid rgba(255, 255, 255, 0.3);
  border-top: 3px solid #ffffff;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

.style-image-item:not(:nth-child(3n)) {
  margin-right: 10px;
}

.scroll-view__content {
  padding-bottom: 20px;
}
</style>
